package com.cskaoyan.controller;

import com.cskaoyan.bean.Storage;
import com.cskaoyan.service.StorageServiceImpl;
import com.cskaoyan.vo.BaseRespVo;
import com.cskaoyan.vo.StorageListVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
public class StorageController {

    @Autowired
    StorageServiceImpl storageService;

    /**
     * 作者：grz
     * 功能：增改商品信息中的图片上传功能
     *
     * @param file 图片文件
     * @return BaseRespVo
     */
    @RequestMapping("/admin/storage/create")
    public BaseRespVo create(@RequestBody MultipartFile file) throws IOException {

        String[] types = {"png", "jpeg", "gif"};

        if (file == null) {
            return BaseRespVo.error("图片上传失败");
        }

        //图片大小验证
        //不通
        long size = file.getSize();
        if (size >= 1048576) {
            return BaseRespVo.error("图片太大");
        }

        String contentType = file.getContentType();
        if (contentType == null) {
            return BaseRespVo.error("图片上传失败");
        }
        boolean flag = false;
        for (String type : types) {
            if (contentType.contains(type)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            //return BaseRespVo.error("不支持的图片类型");
        }

        Storage storage = storageService.insertStorage(file);

        return BaseRespVo.ok(storage);
    }

    /**
     * 作者：grz
     * 功能：获取图片列表
     *
     * @param page  页数
     * @param limit 每页数量限制
     * @param order 正序倒序
     * @param sort  排序方式
     * @param key   表中字段，表示图片新的文件名
     * @param name  表中字段，图片原文件名
     * @return
     */
    @RequestMapping("/admin/storage/list")
    public BaseRespVo list(Integer page, Integer limit, String sort, String order, String key, String name) {

        StorageListVo storageListVo = storageService.list(page, limit, sort, order, key, name);

        return BaseRespVo.ok(storageListVo);
    }


    @RequestMapping("/admin/storage/delete")
    public BaseRespVo delete(@RequestBody Storage storage) {

        int i = storageService.delete(storage);

        if (i == 404) {
            return BaseRespVo.error("图片删除失败");
        }

        return BaseRespVo.ok("图片删除成功");
    }

    @RequestMapping("/admin/storage/update")
    public BaseRespVo update(@RequestBody Storage storage) {

        int i = storageService.update(storage);

        if (i == 404) {
            return BaseRespVo.error("图片修改失败");
        }
        return BaseRespVo.ok("图片修改成功");
    }
}
















